package com.example.webdome.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.webdome.mapper.SetDataMapper;
import com.example.webdome.pojo.Result;
import com.example.webdome.pojo.SetData;
import com.example.webdome.service.SetDataService;
import com.example.webdome.util.decryptToken;
import com.example.webdome.util.spiltUtils;
import com.example.webdome.util.userIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
@Slf4j
public class SetDataServiceImpl extends ServiceImpl<SetDataMapper, SetData> implements SetDataService {
    @Resource
    private SetDataMapper setDataMapper;

    @Resource
    private spiltUtils spiltUtils;
    @Resource
    private userIdUtils userIdUtils;
    @Resource
    private decryptToken decryptToken;

    @Override
    public Result saveSetData(String jsonData, String token) {
        String pe = decryptToken.decrypt(token);
        if (pe != null) {
            String email = spiltUtils.getEmail(pe);
            Integer userId = userIdUtils.getUserId(email);
            QueryWrapper<SetData> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userId", userId);
            setDataMapper.selectOne(queryWrapper);
            remove(queryWrapper);
            SetData setData = new SetData();
            setData.setUserId(userId);
            setData.setJsondata(jsonData);
            int insert = setDataMapper.insert(setData);
            if (insert > 0) {
                return Result.success("保存成功！");
            }
            return Result.failed("保存失败！");
        }
        return Result.failed("您还没有登录！");
    }

    @Override
    public Result getUserSetData(String token) {
        String pe = decryptToken.decrypt(token);
        if (pe != null) {
            String email = spiltUtils.getEmail(pe);
            Integer userId = userIdUtils.getUserId(email);
            QueryWrapper<SetData> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userId",userId);
            SetData setData = setDataMapper.selectOne(queryWrapper);
            return Result.success(setData);
        }
        return Result.failed("您还没有登录！");
    }
}
